import vue from "@vitejs/plugin-vue";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import path from "path";
import { resolve } from "path";
import fs from "fs";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "unplugin-vue-components/resolvers";
import pxtovw from "postcss-px-to-viewport-8-plugin";
import { UserConfig, ConfigEnv, loadEnv } from "vite";
import autoprefixer from "autoprefixer";

function pathResolve(dir: string) {
  return resolve(process.cwd(), ".", dir);
}

const loder_pxtovw = pxtovw({
  //这里是设计稿宽度 自己修改
  viewportWidth: 375,
  viewportUnit: "vw",
  propList: ["*"],
});

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, __dirname);
  const lessResources: Array<string> = [];
  const isBuild = command === "build";
  fs.readdirSync("src/assets/styles").map((dirname) => {
    if (fs.statSync(`src/assets/styles/${dirname}`).isFile()) {
      lessResources.push(`@import "src/assets/styles/${dirname}";`);
    }
  });
  return {
    base: env.NODE_ENV === "development" ? "/" : "./",
    resolve: {
      alias: [
        {
          find: "@",
          replacement: pathResolve("src"),
        },
        {
          find: "views",
          replacement: pathResolve("src/views"),
        },
      ],
    },
    plugins: [
      vue(),
      Components({
        resolvers: [VantResolver()],
      }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
        // 指定symbolId格式
        symbolId: "icon-[dir]-[name]",
        svgoOptions: isBuild,
      }),
    ],
    // css
    css: {
      preprocessorOptions: {
        less: {
          charset: false,
          additionalData: lessResources.join(""),
          modifyVars: {
            "primary-color": "#0080FF",
            "link-color": "#0080FF",
            "border-radius-base": "4px",
          },
          javascriptEnabled: true,
        },
      },
      postcss: {
        plugins: [
          autoprefixer([
            "defaults",
            "not ie < 11",
            "last 2 versions",
            "> 1%",
            "iOS 7",
            "last 3 iOS versions",
          ]),
          loder_pxtovw,
        ],
      },
    },
    // server
    server: {
      hmr: { overlay: false }, // 禁用或配置 HMR 连接 设置 server.hmr.overlay 为 false 可以禁用服务器错误遮罩层
      // 服务配置
      port: 3030, // 类型： number 指定服务器端口;
      open: false, // 类型： boolean | string在服务器启动时自动在浏览器中打开应用程序；
      cors: false, // 类型： boolean | CorsOptions 为开发服务器配置 CORS。默认启用并允许任何源
      host: "0.0.0.0", // IP配置，支持从IP启动
      proxy: {
        ["/api"]: {
          target: env.VITE_APP_API_BASEURL,
          changeOrigin: true,
          rewrite: (path: string) => path.replace(new RegExp("^/api"), ""),
        },
      },
    },
    build: {
      outDir: "dist",
      assetsDir: "assets", //指定静态资源存放路径
      sourcemap: false, //是否构建source map 文件
    },
  };
};
